import requests
import json
ZABBIX_SERVER = "http://server:port/api_jsonrpc.php"
ZABBIX_USER = "<YOUR_USERNAME: such as admin>"  #
ZABBIX_PWD = "<YOUR_PASSWORD: such as 123456>"
TOKEN = ""
DEPENDENT_TRIGGER = "<DEPENDENT_TRIGGER_ID: such as 76480>"
GROUP_NAME = "<MACHINE_GROUP: such as 高灵智腾_系统服务>"
KEYWORDS = "Zabbix agent"


def login(user, password):
    json_param = {
        "jsonrpc": "2.0",
        "method": "user.login",
        "params": {
            "user": user,
            "password": password
        },
        "id": 1,
        "auth": None
    }
    resp = requests.post(ZABBIX_SERVER, json=json_param)
    if resp.status_code == 200:
        result = json.loads(resp.text)["result"]
        return result


def search_triggers(group_name, keywords):
    search_param = {
        "jsonrpc": "2.0",
        "method": "trigger.get",
        "params": {
            "group": group_name,
            "search": {
                "description": keywords
            },
            "output": "triggerid"
        },
        "auth": TOKEN,
        "id": 1
    }
    resp = requests.post(ZABBIX_SERVER, json=search_param)
    if resp.status_code == 200:
        result = json.loads(resp.text)["result"]
        return result


def add_dependencies(trigger_id, depends_on_trigger):

    json_param = {
        "jsonrpc": "2.0",
        "method": "trigger.adddependencies",
        "params": {
            "triggerid": trigger_id,
            "dependsOnTriggerid": depends_on_trigger
        },
        "auth": TOKEN,
        "id": 1
    }
    resp = requests.post(ZABBIX_SERVER, json=json_param)
    print(json.loads(resp.text))


if __name__ == "__main__":
    TOKEN = login(ZABBIX_USER, ZABBIX_PWD)
    triggers = search_triggers(GROUP_NAME, KEYWORDS)
    for trigger in triggers:
        add_dependencies(trigger["triggerid"], DEPENDENT_TRIGGER)

